<template>
  <base-module
    class="weather-comp"
    v-bind="$attrs"
    @icon-click="handleClick"
    v-on="$listeners">
    <div class="custom-title" slot="title">
      <span>{{ $moment().format('YYYY.M.DD') }}</span>
<!--      <img :width="18" :height="18" src="../../assets/images/sun.png" />-->
      <span>26℃</span>
    </div>
    <Histogram class="weather-container" :options="options"></Histogram>
    <ul class="weather-list">
      <li class="weather-item" title="pm">
        <i class="iconfont iconpm"></i>
        <span>{{ weatherList.pm }}</span>
      </li>
      <li class="weather-item" title="噪音">
        <i class="iconfont iconyinliang"></i>
        <span>{{ weatherList.noise }}</span>
      </li>
      <li class="weather-item" title="风速">
        <i class="iconfont iconfengsu"></i>
        <span>{{ weatherList.speed }}</span>
      </li>
      <li class="weather-item" title="湿度">
        <i class="iconfont iconshidu"></i>
        <span>{{ weatherList.humidity }}</span>
      </li>
      <li class="weather-item" title="风向">
        <i class="iconfont iconfengxiang"></i>
        <span>{{ weatherList.direction }}</span>
      </li>
    </ul>
  </base-module>
</template>

<script>
import BaseModule from '@/components/public/BaseModule';
import Histogram from '@/components/echarts/base';
import sunImage from '@/assets/images/sun.png';
import cloudy from '@/assets/images/cloudy.png';
import overcast from '@/assets/images/overcast.png';
import rain from '@/assets/images/rain.png';
import thunderShower from '@/assets/images/thunder_shower.png';

export default {
  name: 'weatherComp',
  data() {
    return {
      // 预报天气信息数据
      forecasts: [],
      // 实况天气数据信息
      lives: [],
      // 城市code
      cityCode: '',
      myCharts: null,
      chartsDom: null,
      weatherRef: `weather${this.$getRandomNum()}`,
      weatherList: {
        pm: 16.7,
        speed: 11,
        noise: '5db',
        direction: '东南风',
        humidity: '47%'
      },
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    options() {
      if (!this.forecasts.length) return {};
      const xAxisData = [];
      const seriesData = [];
      const rich = {
        value: {
          lineHeight: 30,
          align: 'center',
          color: '#fff'
        }
      };
      const casts = this.forecasts[0].casts || [];
      casts.forEach(item => {
        const { date, daytemp, dayweather } = item;
        const richKey = date.replace(/-/g, '');
        xAxisData.push(date);
        seriesData.push(daytemp);
        rich[richKey] = {
          height: 20,
          align: 'center',
          backgroundColor: {
            image: this.setImage(dayweather)
          }
        };
      });
      return {
        grid: {
          // left: 0
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            interval: 0,
            color: '#bac4ff',
            formatter: function (value) {
              const newValue = value.replace(/-/g, '');
              return '{' + newValue + '| }\n{value|' + value.replace(/^\d{4}-/, '') + '}';
              // return '{' + value + '| }\n{value|' + value + ':00' + '}';
            },
            margin: 0,
            rich
          }
        },
        yAxis: {
          type: 'value',
          show: false
        },
        series: [{
          data: seriesData,
          type: 'line',
          smooth: true,
          label: { // 显示数值
            normal: {
              show: true,
              position: 'top'
            }
          },
          areaStyle: { // 改变区域颜色
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(224, 160, 44, .9)'
            }, {
              offset: 0.2,
              color: 'rgba(224, 160, 44, .2)'
            },{
              offset: 0.8,
              color: 'rgba(240, 211, 157, .2)'
            }, {
              offset: 1,
              color: 'transparent'
            }])
          },
          itemStyle: {
            normal: {
              color: '#fff', // 改变折线点的颜色
              lineStyle: {
                color: '#ffb630' // 改变折线颜色
              }
            }
          }
        }]
      };
    }
  },
  components: {
    BaseModule,
    Histogram,
  },
  async created() {
    await this.getWeatherCode();
    this.getWeatherInfo();
  },
  methods: {
    /**
     * 根据项目id获取天气code
     */
    async getWeatherCode() {
      const params = {
        projectId: this.projectId,
      };
      const { success, data: {
        data
      }} = await this.$Model.getWeatherCode(params);
      if (success && data) {
        this.cityCode = data;
      }
    },
    /**
     * 获取天气信息
     * @param extensions {String} 天气类型 all: 天气预报 base: 实时天气
     */
    async getWeatherInfo(extensions = 'all') {
      try {
        const result = await this.$axios({
          url: 'https://restapi.amap.com/v3/weather/weatherInfo',
          method: 'get',
          params: {
            key: 'dec2b0d6f41a26d4ee7ea697d406bee8',
            city: this.cityCode || '350200',
            extensions
          }
        });
        const { status, infocode, forecasts, lives } = result.data;
        if (status === '1' && String(infocode) === '10000') {
          if (extensions === 'all') {
            this.forecasts = forecasts || [];
            return;
          }
          this.lives = lives || [];
        }
      } catch (e) {}
    },
    handleClick() {
      this.$router.push('/environment/weather');
    },
    setImage(type) {
      const types = {
        '多云': cloudy,
        '晴': sunImage,
        '阴': overcast,
        '雨': rain,
        '雷阵雨': thunderShower,
      };
      const currentKey = Object.keys(types).find(key => {
        const reg = new RegExp(`${key}`, 'g');
        return reg.test(type);
      });
      return currentKey ? types[currentKey] : sunImage;
    }
  }
};
</script>

<style lang="scss" scoped>
.weather-comp {
  .weather-container {
    width: 100%;
    height: 150px;
  }
  .weather-list {
    display: flex;
    justify-content: center;
    align-items: start;
    .weather-item {
      width: 75px;
      height: 30px;
      border-radius: 6px;
      display: flex;
      align-items: center;
      padding: 0 4px;
      font-size: 12px;
      background: rgba(141,149,195,0.4);
      color: #fff;
      margin-right: 8px;
      cursor: pointer;
      i {
        margin-right: 12px;
        padding: 2px;
        border-radius: 3px;
        color: #fff;
        &.iconfengxiang {
          margin-right: 7px;
        }
        &.iconpm {
          color: #fff;
          background: #3fadce;
        }
        &.iconyinliang {
          background: #e5452b;
          font-size: 13px;
          padding: 4px;
        }
        &.iconfengsu {
          background: #5373ea;
        }
        &.iconshidu {
          background: #38a9fc;
        }
        &.iconfengxiang {
          font-size: 13px;
          background: #d9be1d;
        }
      }
    }
  }
  .custom-title {
    width: 200px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    span:nth-child(1) {
      font-family: font-lcd;
      font-size: 18px;
    }
  }
}
</style>
